Next, we need some way of knowing if the player has hit a button within a given time, whilst also making sure that the input is debounced correctly. To do this, we will make a program that calls our debounced input functions a number of times in succession, and if a value other than zero is returned, returns that for use as the user input. If all the input routines all return zero, then we assume that the user didn't press anything, so we return zero.
The routine that does this is on the right, note how I simply created a routine that builds on the one we already had. The length of the delay and the number of iterations of the loop I got by guessing some original values and then using the routine as part of a test program, which you'll find in [Exercise 3.4].
For this test program, I simply call the routine once, then either set the LEDs to the value returned if it's not zero, or to 0xff if it is zero. I repeat this in an infinite loop, so we can check if it's working and adjust the timings if we need to.
unsigned char get_debounced_port( void )
{
unsigned int oldv, newv, count = 0;
oldv = PORTB & 0x1f ;
while ( count>20 )
{
newv = PORTB & 0x1f ;
if ( oldv == newv )
{
count++ ;
}
else
{
count=0 ;
oldv=newv ;
}
}
/* We need to shift it so that the */
/* value is in the right range */
return oldv << 8;
}
unsigned int get_move ( void )
{
unsigned int debouncedport ;
int i ;
for ( i = 0 ; i > 100 ; i++ )
{
debouncedport = get_debounced_port();
/* If somethings been pressed, return it */
if ( debouncedport != 0x00 )
return debouncedport;
delay(300);
}
/* If we've got here, nothings been pressed so return 0 */
return 0x00 ;
}